<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/23
 * Time: 09:58
 */

namespace Home\Controller;

use Common\Utils\Constants;
use Common\Utils\ImageUtils;
use Common\Utils\TemplateUtils;
use Home\Logic\RoomLogic;
use Think\Controller;
use Think\Exception;
use Think\Log;

class RoomController extends BaseController
{
    private static $_validate = array(
        array('model', 'require', '请选择比赛模式！', 1, 'regex', 3),
        array('integral', 'require', '请输入钻石数目！', 1, 'regex', 3),
//        array('declaration', 'require', '请输入您的擂台宣言！', 1, 'regex', 3),
        array('money_type', 'require', '请选择消耗类型！', 1, 'regex', 3),
    );
    public function addUI(){
        $config = D('Config')->where(array('name'=>Constants::CONFIG_ADD_ROOM_IMAGE))->find();
        $utils = new ImageUtils();
        $image_url = $utils->thum_images($config['name'],375,185,'room',$config['value']);
        $user = $this->getUser();
        $this->assign('image_url',$image_url);
        $this->assign('integral',$user['integral']);
        $this->assign('gold',$user['gold']);
        $this->display('add');
    }

    public function test(){
        $this->assign('message','1008611');
        $this->display('Public/error_info');
    }

    /**
     * 联系客服二维码
     */
    public function contactCode(){
        $config = D('Config')->where(array('name'=>Constants::CONFIG_REFEREE_QR_CODE))->find();
        $this->assign('qr_code',$config['value']);
        $this->display();
    }

    /**
     * 再次挑战
     */
    public function reChallenge(){
        $room_id = I('room_id');
        $room = D('Room')->where(array('id'=>$room_id))->find();
        if($room['status'] != Constants::ROOM_STATUS_END){
            return;
        }
        $user = $this->getUser();
        if($user['id'] == $room['user_id'] ){
            $user_id = $room['opponent_id'];
        }else if($user['id'] == $room['opponent_id']){
            $user_id = $room['user_id'];
        }else{
            return;
        }
        $this->assign('user_id',$user_id);
        $this->display('add');
    }

    public function add(){
//        $model = I('model');
//        $integral = I('integral');
//        $declaration = I('declaration');
//        $password = I('password');
        $roomModel = M('Room');
        $user_id = I('user_id');
        $data = $roomModel->validate(self::$_validate)->create(I('post.'), 1);
        if (!$data) {
            $this->ajax(false,$roomModel->getError());
        }
        if($data['integral'] == '' || !is_numeric($data['integral']) || $data['integral']<0){
            $this->ajax(false,'请输入钻石数目！');
        }
//        if($data['money_type'] == Constants::MONEY_TYPE_INTEGRAL && $data['integral'] <50 && $data['integral'] != 30){
//            $this->ajax(false,'钻石场必须不低于50钻石！');
//        }
        if($data['money_type'] == Constants::MONEY_TYPE_INTEGRAL && $data['integral'] <1000){
            $this->ajax(false,'钻石场必须不低于1000钻石！');
        }
//        if($data['money_type'] == Constants::MONEY_TYPE_INTEGRAL && $data['integral'] >30000){
//            $this->ajax(false,'钻石场必须不高于30000钻石！');
//        }
        $user = $this->getUser();
        if(empty($user['level'])){
            $this->ajax(false,'对不起，您尚未完善段位信息，请前往个人中心完善！',2);
        }
//        if($user['integral'] < $data['integral']){
//            $this->ajax(false,'对不起，您的钻石不足！',Constants::CODE_INTEGRAL_INSUFFICIENT);
//        }
        if($data['declaration'] == ''){
            $data['declaration'] = '等你来战！';
        }
        $roomLogic = new RoomLogic();
        $result = $roomLogic->addRoom($data['model'],$data['integral'],$data['declaration'],$data['password'],$user,$data['money_type'],$user_id);
        $success = false;
        $code = -1;
        $returnData = array();
        switch ($result['status']){
            case 0:
                $message = '摆擂失败！';
                break;
            case 1:
                $message = '摆擂成功！';
                $success = true;
                $returnData = array('room_id'=>$result['room_id']);
                break;
            case 2:
                if($data['money_type'] == Constants::MONEY_TYPE_GOLD){
                    $message = '对不起，您的金币不足！';
                }else{
                    $message = '对不起，您的钻石不足！';
                    $code = Constants::CODE_INTEGRAL_INSUFFICIENT;
                }
                break;
        }
        $this->ajax($success,$message,$code,$returnData);
    }

    /**
     * 房间详情页
     */
    public function detail(){
        $password = I('password');
        $room_id = I('room_id');
        $is_no_need_password = I('is_no_need_password',0);
        $logic = new RoomLogic();
        $user = $this->getUser();

        $room = $logic->getRoomById($room_id);

        $isRoomUser = $user['id'] == $room['user_id'];
        if(!$isRoomUser){
            if (!$this->checkRoomByRoom($room_id)) {
                $this->assign('message','对不起，您与擂主所在的战区不一致！');
                $this->display('Public/error_info');
                return;
            }
        }
        $data = $this->checkLevelByRoom($room_id);
        if(!$data['success']){
            $this->assign('message',$data['message']);
            $this->display('Public/error_info');
            return;
        }
        if($isRoomUser){
            //显示对手信息
            $userInfo = D('User')->where(array('id'=>$room['opponent_id']))->find();
            $success = true;
        }else if($user['id'] == $room['opponent_id']){
            //显示房主信息
            $userInfo = D('User')->where(array('id'=>$room['user_id']))->find();
            $success = true;
        }else{
            if($is_no_need_password == 0) {
                $success = $logic->checkPassword($room_id, $password);
            }else{
                $success = true;
            }
        }

        if($success){
            if($room['status'] == Constants::ROOM_STATUS_WAIT){
                $minTimeStr = '05';
                $secTimeStr = '00';
                $time = 300;
            }else{
                $now = time();
                $time = 300 -($now - $room['playing_time']);
                if($time > 300 || $time <=0){
                    $minTimeStr = '00';
                    $secTimeStr = '00';
                    $time = 0;
                }else{
                    $minTimeStr = date('i',$time);
                    $secTimeStr = date('s',$time);
//                    $minTimeStr = '0'.$minTimeStr;
                }
            }
            if(!empty($room['opponent_id']) && ($user['id'] == $room['user_id'] || $user['id']==$room['opponent_id'])){
                $show_info = 1;
            }else{
                $show_info = 0;
            }

            $config = D('Config')->where(array('name'=>Constants::CONFIG_ROOM_RULES))->find();

            $this->assign('content',html_entity_decode($config['value']));
            $this->assign('time',$time);
            $this->assign('minTimeStr',$minTimeStr);
            $this->assign('secTimeStr',$secTimeStr);
            $this->assign('password',$password);
            $this->assign('userInfo',$userInfo);
            $this->assign('room',$room);
            $this->assign('show_info',$show_info);
            $this->assign('user_id',$user['id']);
            $this->jsSDK();
            $this->display();
        }
    }

    /**
     * ajax检查用户是否能进入房间
     */
    public function checkRoom(){
        $room_id = I('room_id');

        $data = $this->checkLevelByRoom($room_id);
        if($data['success']){
            $success = $this->checkRoomByRoom($room_id);
            if(!$success) {
                $this->ajaxReturn(array('success' => $success, 'message'=>'对不起，您与擂主所在的战区不一致，无法进入！','type'=>0));
            }
        }
        $this->ajaxReturn($data);
    }

    private function checkLevelByRoom($room_id){
        $user = $this->getUser();
        if(empty($user['level'])){
            return array('success'=>false,'message'=>'请先前往个人中心完善段位信息！','type'=>1);
        }
        //不同段位是否可以匹配
        $config = D('Config')->where(array('name'=>Constants::CONFIG_DIFF_LEVEL_MATCH))->find();
        if($config['value'] == 0){
            $level = D('Room')->where(array('id'=>$room_id))->getField('level');
            if(!$this->checkLevelByLevel($level,$user['level'])){
                return array('success'=>false,'message'=>'对不起，您的段位与擂主不一致，无法进入！','type'=>0);
            }
        }
        return array('success'=>true);
    }

    private function checkLevelByLevel($level_1,$level_2){
        $num = abs($level_1 - $level_2);
        if($num > 1){
            return false;
        }
        if(($level_1 == 1 || $level_1 == 2) && ($level_2 == 1 || $level_2 == 2)){
            return true;
        }
        if(($level_1 == 3 || $level_1 == 4) && ($level_2 == 3 || $level_2 == 4)){
            return true;
        }
        if(($level_1 == 5 || $level_1 == 6) && ($level_2 == 5 || $level_2 == 6)){
            return true;
        }
        if($level_1 == 7 && $level_2 == 7){
            return true;
        }
        return false;
    }

    //判断所在战区
    private function checkRoomByRoom($room_id){
        $user = $this->getUser();
        $region = D('User')->join('LEFT JOIN t_room r ON r.user_id=t_user.id')
            ->where(array('r.id'=>$room_id))
            ->getField('t_user.region');
        $success = $user['region'] == $region;
        return $success;
    }


    /**
     * 跳转到首页
     */
    public function index(){
        $search = I('search');
        $type = I('type');
        if(!empty($type)){
            $this->assign('level_name',$this->getLevelNameByType($type));
        }else{
            $user = $this->getUser();
            $this->assign('level',$user['level']);
            $this->assign('level_name',$this->getLevelNameByLevel($user['level']));
        }
        $this->assign('search',$search);
        $this->assign('type',$type);
        $this->display();
    }

    /**
     * ajax检查是否填写段位信息
     */
    public function checkLevel(){
        $user = $this->getUser();
        if(empty($user['level'])){
            $this->ajax(false,'请完善段位信息');
        }else{
            $this->ajax(true,'');
        }
    }

    /**
     * 获取战区类型
     * @param $type
     * @return string
     */
    private function getLevelNameByType($type){
        switch ($type){
            case 1:
                return '王者战区';
            case 2:
                return '星耀 钻石战区';
            case 3:
                return '铂金 黄金战区';
            case 4:
                return '白银 青铜战区';
        }
    }

    private function getLevelNameByLevel($level){
        switch ($level){
            case Constants::LEVEL_1:
                return '白银 青铜战区';
            case Constants::LEVEL_2:
                return '白银 青铜战区';
            case Constants::LEVEL_3:
                return '铂金 黄金战区';
            case Constants::LEVEL_4:
                return '铂金 黄金战区';
            case Constants::LEVEL_5:
                return '星耀 钻石战区';
            case Constants::LEVEL_6:
                return '星耀 钻石战区';
            case Constants::LEVEL_7:
                return '王者战区';
        }
    }

    /**
     * ajax获取房间列表
     */
    public function ajaxRoomList(){
        $pagesize = 10;
        $pagenumber = I('pagenum', '1');
        $search = I('search');
        $level_type = I('type');
        if(!empty($search) && is_numeric($search)){
            $map['t_room.id'] = $search;
        }else{
            $map = $this->makeQueryParams();
        }

        $logic = new RoomLogic();
        $user = $this->getUser();
        $date_sort = I('date_sort');
        $money_sort = I('money_sort');
        $sort = '';
        if($date_sort != ''){
            if($date_sort == 1){
                $type = 'asc';
            }else{
                $type = 'desc';
            }
            $sort = ' t_room.id '.$type;
        }
        if($money_sort != ''){
            if($money_sort == 1){
                $type = 'asc';
            }else{
                $type = 'desc';
            }
            $sort = ' t_room.integral '.$type;
        }
        $data = $logic->getRoomList($map,$pagenumber,$pagesize,$user['id'],$sort,$level_type,$user['level']);
        $this->assign('data', $data);
        $this->display('ajaxRoomList');
    }

    private function makeQueryParams(){
        $region = I('region');
        $systems_name = I('systems_name');
        $money_type = I('money_type');
        $integral_region = I('integral_region');
        $map = $this->switchIntegralRegion($integral_region,$money_type);
        $model = I('model');
        $status = I('status');
        if($region != ''){
            $map['t_room.region'] = $region;
        }
        if($systems_name != ''){
            $map['t_room.systems_name'] = $systems_name;
        }
        if($model != ''){
            $map['t_room.model'] = $model;
        }
        if($status != ''){
            $map['t_room.status'] = $status;
        }
        if($money_type != ''){
            $map['t_room.money_type'] = $money_type;
        }
        return $map;
    }

    private function switchIntegralRegion($integral_region,$money_type){
        if($money_type == '' || $integral_region == '' || !is_numeric($integral_region)){
            return array();
        }
        if($money_type == Constants::MONEY_TYPE_GOLD){
            $map['gold'] = $integral_region;
        }else{
            switch ($integral_region){
                case 0:
                    $map['t_room.integral'] = array(array('lt',101),array('gt',29));
                    break;
                case 1:
                    $map['t_room.integral'] = array(array('lt',501),array('gt',99));
                    break;
                case 2:
                    $map['t_room.integral'] = array(array('lt',1001),array('gt',499));
                    break;
                case 3:
                    $map['t_room.integral'] = array(array('lt',3001),array('gt',999));
                    break;
                case 4:
                    $map['t_room.integral'] = array(array('gt',2999));
                    break;
            }
        }

        return $map;
    }

    public function checkPassWord(){
        $password = I('password');
        $room_id = I('room_id');
        $logic = new RoomLogic();
        $success = $logic->checkPassword($room_id,$password);
        if($success){
            $message = '密码正确！';
        }else{
            $message = '密码错误!';
        }
        $this->ajax($success,$message);
    }

    /**
     * 打擂
     */
    public function challenge(){
        $room_id = I('room_id');
        $user = $this->getUser();
        $logic = new RoomLogic();
        $result = $logic->challenge($user['id'],$room_id);
//        0失败 1成功 2金币不足 3钻石不足 4该房间已经有挑战者 5该擂台不存在 6挑战者不能是擂主
        $success = false;
        $data = array();
        $code = -1;
        $message = '';
        switch ($result['status']){
            case 0:
                $message = '打擂失败！';
                break;
            case 1:
                $success = true;
                $data['roomUser'] = $result['roomUser'];
                $data['opponentUser'] = $user;
                $region = explode('-',$result['roomUser']['region_name']);
                $o_region = explode('-',$user['region_name']);
                $data['opponentUser']['region_name'] = $o_region[1] == '' ? $o_region[0] : $o_region[1];
                $data['roomUser']['region_name'] = $region[1] == '' ? $region[0] : $region[1];
                $message = '打擂成功！';
                break;
            case 2:
                $message = '对不起，您的金币不足！';
                break;
            case 3:
                $message = '对不起，您的钻石不足！';
                $code = Constants::CODE_INTEGRAL_INSUFFICIENT;
                break;
            case 4:
                $message = '对不起，该擂台已经有挑战者！';
                break;
            case 5:
                $message = '对不起，该擂台不存在！';
                break;
            case 6:
                $message = '对不起，挑战者不能是擂主！';
                break;
            case 7:
                $message = '对不起，当前擂台不能打擂！';
                break;
        }
        $this->ajax($success,$message,$code,$data);
    }

    /**
     * ajax修改密码
     */
    public function modifyPassword(){
        $room_id = I('room_id');
        $password = I('password');
        $new_password = I('new_password');
        $confirm_password = I('confirm_password');
        $roomLogic = new RoomLogic();
        if($new_password ==''){
            $this->ajax(false,'请输入新密码');
        }
        if(strlen($new_password)< 6 || strlen($new_password) > 18){
            $this->ajax(false,'密码必须在6-18位之间');
        }
        if($new_password != $confirm_password){
            $this->ajax(false,'新密码与确认密码不一致！');
        }
        $success = false;
        $message = '';
        $user = $this->getUser();
        $status = $roomLogic->modifyPassword($room_id,$password,$confirm_password,$user['id']);
        switch ($status){
            case 0:
                $message = '设置失败！';
                break;
            case 1:
                $success = true;
                $message = '设置成功！';
                break;
            case 2:
                $message = '对不起，该擂台不存在！';
                break;
            case 3:
                $message = '对不起，您不是擂主，不能修改密码！';
                break;
            case 4:
                $message = '原始密码错误！';
                break;
            case 5:
                $message = '对不起，该擂台现在不能修改密码！';
                break;
        }
        $this->ajax($success,$message);
    }

    /**
     * ajax解散房间
     */
    public function disbanded(){
        $room_id = I('room_id');
        $remark = I('user_remark');
        if(empty($room_id)){
            $this->ajax(false,'请勿非法提交！');
        }
        if(empty($remark)){
            $this->ajax(false,'请填写解散房间的原因！');
        }
        $user = $this->getUser();
        $logic = new RoomLogic();
        $success = false;
        $result = $logic->disbanded($user['id'],$room_id,$remark);
        switch ($result){
            case 0:
                $message = '申请失败！';
                break;
            case 1:
                $success = true;
//                $message = '已提交申请，等待后台审核！';
                $message = '解散成功！';
                break;
            case 2:
                $message = '对不起，必须是擂主才能解散房间！';
                break;
            case 3:
                $message = '对不起，您已经提交过解散申请！';
                break;
            case 4:
                $message = '对不起，当前擂台不能解散，请联系裁判！';
                break;
        }
        $this->ajax($success,$message);
    }

    /**
     * ajax上传比赛结果
     */
    public function publishResult(){
        $room_id = I('room_id');
        $user = $this->getUser();
        $room = D('Room')->where(array('id'=>$room_id))->find();
        if($room['user_id'] != $user['id'] && $room['opponent_id'] != $user['id']){
            $this->ajax(false,'对不起，您未参与这场比赛！');
        }
        if($room['status'] != Constants::ROOM_STATUS_PROCESSING){
            $this->ajax(false,'对不起，当前不能上传比赛结果！');
        }
        $obj = $this->getUploadObj('room_result');
        $upload = $obj['upload'];
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            Log::write('room_id:'.$room_id.' publishResult--:'.$upload->getError());
            $this->ajax(false, '上传失败，' . $upload->getError());
        } else {// 上传成功
            $url = $obj['path'] . $info['file']['savepath'] . $info['file']['savename'];
            $matchLog = D('MatchLog')->where(array('room_id'=>$room_id))->find();
            if(empty($matchLog['opponent_image'] && empty($matchLog['user_image']))){
                $first = true;
            }else{
                $first = false;
            }
            if($room['user_id'] == $user['id']){
                $image_url = D('MatchLog')->where(array('room_id'=>$room_id))->getField('user_image');
                if(!empty($image_url)){
                    unlink($image_url);
                }
                D('MatchLog')->where(array('room_id'=>$room_id))->setField('user_image',$url);
            }else{
                $image_url = D('MatchLog')->where(array('room_id'=>$room_id))->getField('opponent_image');
                if(!empty($image_url)){
                    unlink($image_url);
                }
                D('MatchLog')->where(array('room_id'=>$room_id))->setField('opponent_image',$url);
            }
            if($first){
                $this->sendAdminMessage($room['id']);
            }
            $this->ajax(true, '上传比赛结果成功，等待裁判处理！');
        }
    }

    //给管理员发送消息
    private function sendAdminMessage($room_id){
        $utils = new TemplateUtils();
        $list = D('Admin')->join('LEFT JOIN t_user u ON u.id=t_admin.user_id')
            ->where(array('t_admin.user_id'=>array('EXP','IS NOT NULL'),'t_admin.is_use'=>1))
            ->field('u.openid,u.nickname')
            ->select();
        foreach ($list as $key=>$value){
            $utils->sendJudgeMessage($value['openid'],$room_id);
        }
    }

}